package com.google.code.sfa.tigr;

import java.lang.Math;
import com.google.code.sfa.util.OverlapAlignment;
public class MatchCriteria {

    private int minOverlap;
    private int maxOverhang;
    private double minScoreRatio;
    private int maxLocalErrors;

    public int errors;

    public MatchCriteria( int minOverlap, int maxOverhang, double minScoreRatio, int maxLocalErrors) {
	this.minOverlap = minOverlap;
	this.maxOverhang = maxOverhang;
	this.minScoreRatio = minScoreRatio;
	this.maxLocalErrors = maxLocalErrors;
    }

    public boolean testMatch( OverlapAlignment alignment) {
	int overlap = alignment.alignment.length();
	if( overlap < minOverlap) {
	    //System.out.println("Overlap: " + overlap);
	    return false;
	}

	int overhang = Math.max( Math.abs( alignment.offset - 1), Math.abs( alignment.reverseOffset - 1));
	if( overhang > maxOverhang) {
	    //System.out.println("offset: " + alignment.offset + " reverse: " + alignment.reverseOffset);
	    //System.out.println("Overhang: " + overhang);
	    return false;
	}

	double scoreRatio = ((double) alignment.score) / (5*alignment.alignment.length());
	if( scoreRatio < minScoreRatio ) {
	    //System.out.println("scoreRatio: " + scoreRatio);
	    return false;
	}

	int localErrors = getLocalErrors( alignment, 32);
	
	if( localErrors > maxLocalErrors) {
	    //System.out.println("localErrors: " + localErrors);
	    return false;
	}
	return true;
    }

    protected int getLocalErrors( OverlapAlignment a, int window) {
	int[] localErrors = new int[window];
	int pos = 0;
	int maxErrors = 0;
	this.errors = 0;
	for( int i = 1; i <= a.alignment.length(); i++) {
	    if( a.alignment.symbolAt("subject",i) != a.alignment.symbolAt("query",i)) {
		this.errors++;
		for( int ii = 0; ii < window; ii++){
		    localErrors[ii]++;
		}
	    }

	    pos++;
	    if( pos == window) {
		pos = 0;
	    }

	    if( localErrors[pos] > maxErrors) {
		maxErrors = localErrors[pos];
	    }
	    localErrors[pos] = 0;
	}

	return maxErrors;
    }

}
